package com.lwl.Algorithmic_data_structure.二叉树递归套路;

public class 是否平衡二叉树 {
    class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    class Ret{
        int height;
        boolean isBalanced;
        public Ret(int height, boolean isBalanced) {
            this.height = height;
            this.isBalanced = isBalanced;
        }
    }
    public boolean is_Balanced(TreeNode root){
        return process(root).isBalanced;
    }

    private Ret process(TreeNode root) {
        if (root == null){
            return new Ret(0,true);
        }
        Ret left = process(root.left);
        Ret right = process(root.right);
        if (left.isBalanced == false || right.isBalanced == false){
            return new Ret(0,false);
        }
        if (Math.abs(left.height - right.height) > 1){
            return new Ret(0,false);
        }
        return new Ret(Math.max(left.height,right.height) + 1,true);
    }

}
